<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Link extends Admin_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('links_m');
    }

    public function index()
    {
        $links         = $this->links_m->select();
        $data['links'] = $links;
        $this->load->view('links/index', $data);
    }

    public function add()
    {
        $data['pic_path'] = "[]";
        $data['pic_con']  = json_encode([]);
        $this->load->view('links/form', $data);
    }

    public function edit($id = null)
    {
        $links = $this->links_m->find($id);
        if (!$links) {
            show_message('参数错误！', site_url(X_URL . 'Link/index'));
        }
        $del_url = base_url("index.php/Upload/delete_img?url=" . $links['img']);;
        $pic_con[]        = [
            'caption' => "产品图",
            'size'    => 576237,
            'width'   => '120px',
            'url'     => $del_url,
            "key"     => $links['id'],
        ];
        $data['pic_path'] = "['" . $links['img'] . "']";
        $data['pic_con']  = json_encode($pic_con);
        $data['links']    = $links;
        $this->load->view('links/form', $data);
    }

    public function del($id)
    {
        if ($id) {
            if ($this->links_m->delete($id)) {
                show_message('恭喜，删除成功！', site_url(X_URL . 'Link/index'), 1);
            } else {
                show_message('参数错误！', site_url(X_URL . 'Link/index'));
            }
        } else {
            $this->error('参数错误！');
        }
    }

    public function update()
    {
        $post          = $this->input->post();
        $data['title'] = $post['title'];
        $data['url']   = $post['url'] ?? "";
        $data['img']   = $post['img'] ?? "";
        $data['o']     = $post['o'] ?? 999;
        $data['hide']  = $post['hide'] ?? 0;
        $id            = $post['id'] ?? 0;
        if ($data['title'] == '') {
            show_message('名称不能为空！', site_url(X_URL . 'Link/index'));
        }
        if (!$id) {
            $this->links_m->insert($data);
        } else {
            $this->links_m->update(['id' => $id], $data);
        }
        show_message('恭喜，操作成功！', site_url(X_URL . 'Link/index'), 1);
    }
}

